<?php
/**
 * This example decorator wraps things in div blocks for example
 */
class Forms_Decorators_Wrap extends Zend_Form_Decorator_Abstract
{
	private $tag;
	private $attribs;
	
	/**
	 * Initialise le decorator
	 */
	public function __construct($options = null)
    {
    	if (!is_array($options) || !array_key_exists('tag', $options)) {
    		$options = array ('tag' => 'div');
    	}
    	$this->tag = $options['tag'];
    	unset($options['tag']);
    	$this->attribs = $options;
    }    
    
    /**
     * Get the formatted open tag
     * 
     * @param  string $tag 
     * @param  array $attribs 
     * @return string
     */
    protected function _getOpenTag($tag, array $attribs = null)
    {
        $html = '<' . $tag;
        if (null !== $attribs) {
            $html .= $this->_htmlAttribs($attribs);
        }
        $html .= '>';
        return $html;
    }

    /**
     * Get formatted closing tag
     * 
     * @param  string $tag 
     * @return string
     */
    protected function _getCloseTag($tag)
    {
        return '</' . $tag . '>';
    }

    /**
     * Convert options to tag attributes
     * 
     * @return string
     */
    protected function _htmlAttribs(array $attribs)
    {
        $xhtml = '';
        foreach ((array) $attribs as $key => $val) {
            $key = htmlspecialchars($key, ENT_COMPAT, 'UTF-8');
            if (is_array($val)) {
                $val = implode(' ', $val);
            }
            $val    = htmlspecialchars($val, ENT_COMPAT, 'UTF-8');
            $xhtml .= " $key=\"$val\"";
        }
        return $xhtml;
    }
	
    public function render($content)
    {
        return $this->_getOpenTag($this->tag, $this->attribs). $content . $this->_getCloseTag($this->tag);
    }
}